package simple.web;

import java.io.StringReader;

import net.sourceforge.stripes.action.DefaultHandler;
import net.sourceforge.stripes.action.HandlesEvent;
import net.sourceforge.stripes.action.Resolution;
import net.sourceforge.stripes.action.StreamingResolution;
import net.sourceforge.stripes.action.UrlBinding;

import net.sourceforge.stripes.validation.Validate;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import simple.persistence.entity.User;

@UrlBinding("/UsersAjax.action")
public class UsersAjaxActionBean extends BaseActionBean {

    @Validate(required = true, on = {"view"})
    private Boolean debug;

    public Boolean getDebug() {
        return debug;
    }

    public void setDebug(Boolean debug) {
        this.debug = debug;
    }

    @DefaultHandler
    @HandlesEvent("view")
    public Resolution view() throws JSONException {
        JSONArray userList = new JSONArray();
        for (User user : getUserManager().getUsers()) {
            JSONObject u = new JSONObject();
            u.put("firstName", user.getFirstName());
            u.put("lastName", user.getLastName());
            u.put("birthday", user.getBirthday());
            userList.put(u);
        }
        return new StreamingResolution("text", new StringReader(userList.toString()));
    }

}
